package magicloan.auctionpocket.util;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import magicloan.auctionpocket.MyApplication;

/**
 * Created by Sunny on 2016/10/2.
 */
public class UiUtils {
    private static Context context = MyApplication.instance.getApplicationContext();

    /**
     * 将像素值转化为对应的dp值
     */
    public static int dp2px(double dp) {
        float density = context.getResources().getDisplayMetrics().density;
        int px = (int) (dp * density + .5);
        return px;
    }

    /**
     * 将dp值转化为对应的像素值
     */
    public static int px2dp(double px) {
        float density = context.getResources().getDisplayMetrics().density;
        int dp = (int) (px / density + .5);
        return dp;
    }

    // 最新消息在屏幕头部弹框的显示动画效果
    @SuppressLint("WrongConstant")
    public static void showNewMessageNotify(final RelativeLayout rl_new_message) {
        rl_new_message.setAlpha(0);
        rl_new_message.setTop(-UiUtils.dp2px(10));
        rl_new_message.setVisibility(View.VISIBLE);

        ValueAnimator animFloat = ValueAnimator.ofFloat(0, 1);
        animFloat.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alapha = (float) animation.getAnimatedValue();
                rl_new_message.setAlpha(alapha);
                rl_new_message.invalidate();
            }
        });
        animFloat.setDuration(500);

        ValueAnimator animInteger = ValueAnimator.ofInt(-UiUtils.dp2px(10), 0);
        animInteger.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int top = (int) animation.getAnimatedValue();
                rl_new_message.setTop(top);
                rl_new_message.invalidate();
            }
        });
        animInteger.setDuration(500);

        animFloat.start();
        animInteger.start();
    }

    // 最新消息在屏幕头部弹框的隐藏动画效果
    @SuppressLint("WrongConstant")
    public static void hidNewMessageNotify(final RelativeLayout rl_new_message) {
        rl_new_message.setAlpha(1);
        rl_new_message.setTop(0);
        ValueAnimator animFloat = ValueAnimator.ofFloat(1, 0);
        animFloat.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alapha = (float) animation.getAnimatedValue();
                rl_new_message.setAlpha(alapha);
                rl_new_message.invalidate();
                if (alapha == 0) {
                    rl_new_message.setVisibility(View.GONE);
                }
            }
        });
        animFloat.setDuration(1000);

        ValueAnimator animInteger = ValueAnimator.ofInt(0, -UiUtils.dp2px(10));
        animInteger.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int top = (int) animation.getAnimatedValue();
                rl_new_message.setTop(top);
                rl_new_message.invalidate();
            }
        });
        animInteger.setDuration(1000);

        animFloat.start();
        animInteger.start();
    }

    /**
     * 获取屏幕的高度
     */
    @SuppressLint("WrongConstant")
    public static int getScreenHeight() {
        WindowManager windowManager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
        return windowManager.getDefaultDisplay().getHeight();
    }

    /**
     * 获取屏幕的宽度
     */
    @SuppressLint("WrongConstant")
    public static int getScreenWidth() {
        WindowManager windowManager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
        return windowManager.getDefaultDisplay().getWidth();
    }

    /**
     * 将View转为Bitmap的方法
     */
    @SuppressLint("WrongConstant")
    public static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    /**
     * 获取状态栏的高度
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
//            Log.v("@@@@@@", "the status bar height is : " + statusBarHeight);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 设置添加屏幕的背景透明度
     */
    public static void backgroundAlpha(final Activity context, float bgAlphaStart, float bgAlphaEnd, long duration) {
        final WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlphaStart;

        ValueAnimator valueAnimator = ValueAnimator.ofFloat(bgAlphaStart, bgAlphaEnd);
        valueAnimator.setDuration(duration);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float newAlpha = (float) animation.getAnimatedValue();
                lp.alpha = newAlpha;
                context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                context.getWindow().setAttributes(lp);
            }
        });
        valueAnimator.start();
    }

    /**
     * 将bitmap图片转化为字节码存储或进行网络传输
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 70, baos);
        return baos.toByteArray();
    }

    public static Bitmap makeSmallBitmap(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.7f, 0.7f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    /**
     * 获取是否存在NavigationBar
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hasNavigationBar;
    }

    /**
     * 获取控件所显示的bitmap
     */
    public static Bitmap getViewBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }
}
